package cn.amos.server.biz.impl;

import cn.amos.server.biz.LoginService;
import cn.amos.server.request.LoginForm;
import cn.amos.server.request.RegisterForm;
import cn.amos.server.response.LoginInfoVO;
import org.springframework.beans.BeanUtils;

import javax.jws.WebMethod;
import javax.jws.WebService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * PROJECT: ws-gateway
 * DESCRIPTION: 登录相关实现
 *
 * @author amos.wang
 * @date 2019/4/12
 */
@WebService(serviceName = "WsLoginService",
        targetNamespace = "service.ws.server.amos.cn",
        endpointInterface = "cn.amos.server.ws.service.WsLoginService")
public class LoginServiceImpl implements LoginService {
    private static AtomicLong USER_ID = new AtomicLong(100);
    private static Map<String, LoginInfoVO> USER_ID_LOGIN_INFO = new HashMap<String, LoginInfoVO>();
    private static Map<String, String> PHONE_USER_ID = new HashMap<String, String>();

    @Override
    public LoginInfoVO register(RegisterForm registerForm) {
        String phoneNo = registerForm.getPhoneNo();
        if (PHONE_USER_ID.get(phoneNo) != null) {
            throw new RuntimeException("用户已存在");
        }

        LoginInfoVO loginInfoVO = new LoginInfoVO();
        BeanUtils.copyProperties(registerForm, loginInfoVO);
        String token = "TOKEN" + getUserId();
        loginInfoVO.setToken(token);
        PHONE_USER_ID.put(phoneNo, token);
        USER_ID_LOGIN_INFO.put(token, loginInfoVO);

        return loginInfoVO;
    }

    @Override
    public LoginInfoVO login(LoginForm loginForm) {
        String phoneNo = loginForm.getPhoneNo();
        String token = PHONE_USER_ID.get(phoneNo);
        if (token == null) {
            throw new RuntimeException("用户不存在");
        }

        return USER_ID_LOGIN_INFO.get(token);
    }

    @Override
    public LoginInfoVO getLoginInfo(String token) {
        LoginInfoVO loginInfoVO = USER_ID_LOGIN_INFO.get(token);
        if (loginInfoVO == null) {
            throw new RuntimeException("用户不存在");
        }

        return loginInfoVO;
    }

    @Override
    @WebMethod(exclude = true)
    public List<LoginInfoVO> hasLogin() {
        return new ArrayList<LoginInfoVO>(USER_ID_LOGIN_INFO.values());
    }

    /**
     * 生成用户ID
     *
     * @return 用户ID
     */
    private static Long getUserId() {
        return USER_ID.incrementAndGet();
    }
}
